package com.xjtu.project.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjtu.project.common.utls.SessionUtilsUser;
import com.xjtu.project.mapper.CartMapper;


import com.xjtu.project.model.domain.Cart;
import com.xjtu.project.model.domain.Shoe;
import com.xjtu.project.service.CartService;
import com.xjtu.project.service.ShoeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;


/**
* @author 86185
* @description 针对表【cart】的数据库操作Service实现
* @createDate 2025-07-04 17:38:05
*/
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart>
    implements CartService {
    @Autowired
    private ShoeService shoeService;
    @Override
    public void add(Integer shoeId, Integer size) {
        Cart cart = new Cart();
        Shoe shoe = shoeService.getById(shoeId);
        cart.setShoeId(shoeId);
        cart.setName(shoe.getName());
        cart.setImage(shoe.getImage());
        cart.setSize(size);
        cart.setUserId(SessionUtilsUser.getCurrentUserInfo().getId());
        //先查有没有对应的购物车信息，如果有这双鞋了就直接加数量就好了
        Cart one = lambdaQuery().eq(Cart::getShoeId, shoeId)
                .eq(Cart::getUserId, SessionUtilsUser.getCurrentUserInfo().getId())
                .one();
        if(one!=null){
            Integer num=one.getNumber();
            lambdaUpdate().eq(Cart::getShoeId, shoeId).eq(Cart::getUserId,  SessionUtilsUser.getCurrentUserInfo().getId()).set(Cart::getNumber, num+1).set(Cart::getAmount, shoe.getPrice().multiply(BigDecimal.valueOf(num+1))).update();
        }
        else{
            cart.setAmount(shoe.getPrice());
            cart.setNumber(1);
            save(cart);
        }

    }

    @Override
    public void sub(Integer shoeId) {
        //删除一个购物车商品如果数量为1 直接删，如果数量不为1就修改数量
        Cart one = lambdaQuery().eq(Cart::getShoeId, shoeId).eq(Cart::getUserId,  SessionUtilsUser.getCurrentUserInfo().getId()).one();
        Shoe shoe = shoeService.getById(shoeId);
        if(one!=null){
            Integer num=one.getNumber();
            if(num==1){
                removeById(one.getId());
            }
            else{
                lambdaUpdate().eq(Cart::getShoeId, shoeId).set(Cart::getNumber, num-1).set(Cart::getAmount, one.getAmount().subtract(shoe.getPrice())).update();
            }
        }
    }
}




